package com.it.xyx;

import com.it.xyx.demo.entity.User;
import com.it.xyx.demo.service.IUserService;
import jakarta.annotation.Resource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

/**
 * @Classname UserRealm 自定义Realm，继承AuthorizingRealm类，重写认证和授权方法
 * @Description TODO
 * @Date 2024/8/23 20:09
 * @Created by 潜伏Sir
 */
public class UserRealm extends AuthorizingRealm {

    @Resource
    IUserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入授权方法！");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 获取当前登录用户
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        //获得权限列表
        authorizationInfo.addStringPermission(user.getPers());

        return authorizationInfo;
    }


    //认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("进入认证方法！");
        User user = userService.lambdaQuery()
                .eq(User::getUsername, authenticationToken.getPrincipal()).one();
        if (user == null) { // 用户名校验
            return null;
        }
        // 将token进行转换，token是前端页面传过来的用户名+密码的加密封装
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        // 用户名校验
        if (!usernamePasswordToken.getUsername().equals(user.getUsername())) {
            return null;  // 返回null的话，会自动抛出UnknownAccountException异常
        }
        // 密码校验，Shiro自动完成
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");

    }
}
